-- Chancellor
-- Created by chengb Jul/26/2016
-- 大臣格子

local CHANCELLOR_PET_ID = 5;   -- 大臣对应的冈布奥编号

-- 内部函数声明
local talkFirstTime;
local talkBeforeRescue;
local talkAfterResue;

-- 初始化
function initChancellor(self)
    self.item:removeAllChildren();

    local class = self.gridData.class;
    local buildingInfo = BuildingBonusM.queryBuildingView(class);

    if not buildingInfo then
        error("获取不到建筑查看配置，元素类型：" .. class);
        return;
    end

    local iconPath = getHeroIconPath(CHANCELLOR_PET_ID);

    local function onClicked(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            if self.gridData.state == GRID_STATE_DISABLE then
                -- 已经失效，不处理
                return;
            end

            -- 更新建筑访问
            self:updateBuildingVisit();

            -- 音效
            AudioM.playFx("ui_open1");

            if BraveVSDragonM.hasDefeatedDragon() then
                -- 击败龙王后，打开建筑查看界面
                self:openBuildingView(nil, nil, nil, nil, nil, iconPath);
            elseif BraveVSDragonM.hasRescuedPrincess() then
                -- 救出公主后
                talkAfterResue(self, iconPath);
            elseif not BraveVSDragonM.hasTalkedWithRole(self.gridData.type, 1) then
                -- 救出公主前，首次对话
                talkFirstTime(self);
            else
                -- 救出公主前，播放对话
                talkBeforeRescue(self);
            end
        end
    end

    self.icon = ccui.ImageView:create(iconPath);
    self.icon:setTouchEnabled(true);
    self.icon:addTouchEventListener(onClicked);
    self.item:addChild(self.icon);
    self.iconPath = iconPath;
    self.icon:setPosition(cc.p(0, -15));
    self.icon:setScale(1.2);

    -- 呼吸
    self.needAnimation = true;
end

-- 首次对话
function talkFirstTime(self)
    DungeonActionM.go("talk_with_brave_role", self.gridData:getPos(), 1);

    startDialogueTemplate("chancellor_talk1");
end

-- 救出公主前，播放对话
function talkBeforeRescue(self)
    startDialogueTemplate("chancellor_talk2");
end

-- 救出公主之后播放对话
function talkAfterResue(self, iconPath)
    -- 如果还没领取大臣的奖励
    if not BraveVSDragonM.hasGotBuildingBonus(self.gridData.class) then
        -- 播放对话
        local function endEffect()
            -- 领取大臣的奖励
            DungeonActionM.go("brave_building_bonus", self.gridData:getPos())
        end
        startDialogueTemplate("chancellor_talk3", endEffect);
    else
        -- 已经领取了奖励
        local buildingInfo = BuildingBonusM.queryBuildingView(self.gridData.class);
        self:openBuildingView(nil, nil, buildingInfo["dialog2"], nil, nil, iconPath);
    end
end